package com.quickcode.example.collection;

import com.quickcode.annotation.Safe;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by 张波 on 2019/10/23.
 */
@Slf4j
@Safe
public class LocalDateFormatExample {

    public static final int clientTotal = 5000;

    public static final int threadTotal = 200;

    public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
//                    parse();
                    format(count);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception:{}", e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            log.info("开始进入线程等待");
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("exception:{}", e);
        }
        executorService.shutdown();
    }

    /**
     * 线程不安全，会报异常
     */
    private static void parse() {
        dateTimeFormatter.parse("20191023");
    }

    /**
     * format执行时倒没报异常
     *
     * @param i
     */
    private static void format(int i) {
        dateTimeFormatter.format(LocalDateTime.now());
    }
}
